package com.heima.admin.serevce.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.serevce.IAdminService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;

@Service
public class AdminServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements IAdminService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.判断用户是否存在
        if (!StringUtils.isBlank(dto.getName()) && !StringUtils.isBlank(dto.getPassword())) {
            //1.2查询用户
            AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
            if (adUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //1.3密码验证
            String salt = adUser.getSalt();
            String password = dto.getPassword();
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!password.equals(adUser.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.4返回数据jwt
            HashMap<String, Object> map = new HashMap<>();
            adUser.setSalt("");
            adUser.setPassword("");
            adUser.setLoginTime(new Date());
            map.put("user", adUser);
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            return ResponseResult.okResult(map);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
    }
}
